import _ from 'lodash';
import * as api from '@/services/SystemMgr';
import * as utils from '../utils/method';

const Model = {
  namespace: 'SystemManageItems',
  state: {
    originalTree: [],
    orgTree: [],
    expandedKeys: ['00000000'],
  },
  effects: {
    *init({ payload, callback }, { call, put }) {
      const response = yield call(api.getOrgTreeListUsingGET, payload);
      if (response && !_.isEmpty(response.data)) {
        const newTree = utils.addParentElement(response.data);
        const orgTree = utils.orgBluidTree(newTree);
        yield put({
          type: 'save',
          payload: { orgTree, originalTree: newTree },
        });
      }
    },
  },
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    searchOrgTree(state, action) {
      const originalTree = _.cloneDeep(state.originalTree);
      const resultTree =
        action.payload !== '' ? utils.buildTree(originalTree, action.payload) : originalTree;
      const orgTree = utils.orgBluidTree(
        action.payload !== '' ? resultTree.newTreeArr : originalTree,
      );
      return {
        ...state,
        orgTree,
        expandedKeys: action.payload !== '' ? _.flattenDeep(resultTree.expandedKeys) : ['00000000'],
      };
    },
  },
};

export default Model;
